﻿package com.neriksworkshop.colourLoversDemos.wordPatches
{
	import com.neriksworkshop.colourLoversDemos.wordPatches.view.*;
	import com.neriksworkshop.lib.colourLovers.events.RequestEvent;
	import com.neriksworkshop.lib.colourLovers.items.IGraphicItem;
	import com.neriksworkshop.lib.colourLovers.RequestManager;
	import com.neriksworkshop.lib.colourLovers.requests.ColorRequest;
	import com.neriksworkshop.lib.colourLovers.requests.IGraphicRequest;
	import com.neriksworkshop.lib.colourLovers.requests.PaletteRequest;
	import com.neriksworkshop.lib.colourLovers.requests.params.OrderCol;
	import com.neriksworkshop.lib.colourLovers.requests.PatternRequest;
	import flash.display.Sprite;
	import flash.display.StageAlign;
	import flash.display.StageScaleMode;
	import flash.events.Event;

	
	/**
	 * ...
	 * @author Erik
	 */
	public class MainController extends Sprite
	{
		private var rm:RequestManager;
		
		private var mainView:MainView;
		
		private var transactionIds:/*int*/Array = new Array();
		
		private var searchOptions:Array = [true, false, false];
		
		public function MainController() 
		{
			stage.scaleMode = StageScaleMode.NO_SCALE;
			stage.align = StageAlign.TOP_LEFT;
			rm = RequestManager.getInstance();
			
			mainView = new MainView()
			mainView.addEventListener('patchAdded', onPatchAdded);
			addChild(mainView);
		}
		
		private function onPatchAdded(e:Event):void 
		{
			var patch:Patch = e.target as Patch;
			
			var paletteReq:PaletteRequest = new PaletteRequest();
			var patternReq:PatternRequest = new PatternRequest();
			
			paletteReq.keywords = patternReq.keywords = patch.text.split(" ");
			paletteReq.keywordExact = true;
			paletteReq.numResults = patternReq.numResults = 20;
			paletteReq.orderCol = patternReq.orderCol = OrderCol.RANK;
			paletteReq.extraData = patternReq.extraData = patch.id;
			
			paletteReq.addEventListener(RequestEvent.RESULTS, onRequestComplete);
			patternReq.addEventListener(RequestEvent.RESULTS, onRequestComplete);
			
			rm.sendRequests(paletteReq, patternReq);
			
			
			/*
			var soReqs:Array = [ColorRequest, PaletteRequest, PatternRequest];
			for (var i:int = 0; i < 3; i++) { if (!searchOptions[i]) soReqs.splice(i, 1);	}
			var reqClass:Class = soReqs[Math.floor(Math.random()*soReqs.length)];
			
			var req:IGraphicRequest;
			req = new reqClass();
			req.keywords = [patch.text];
			req.keywordExact = true;
			
			req.orderCol = OrderCol.RANK;
			req.numResults = 1;
			req.extraData = patch.id;
			req.addEventListener(RequestEvent.RESULTS, onRequestComplete);
			
			rm.request(req);*/
					
			
			//trace(patch.id, patch.text);
		}
		
		private function onRequestComplete(e:RequestEvent):void 
		{
			var req:IGraphicRequest = (e.target as IGraphicRequest);
			
			mainView.setPatchData(req.extraData, req.items, (req is PaletteRequest) ? "palettes" : "patterns")
			

			
		}
		
	}
	
}